package com.ruoyi.classinfo.controller;

import org.apache.commons.codec.digest.HmacUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.*;

@RestController
@RequestMapping("/api/ai")
public class AIController {

    @Value("${spark.appId}")
    private String appId;

    @Value("${spark.apiKey}")
    private String apiKey;

    @Value("${spark.apiSecret}")
    private String apiSecret;

    @PostMapping("/chat")
    public ResponseEntity<Map<String, Object>> chat(@RequestBody Map<String, Object> request) {
        try {
            // 1. 生成签名
            String date = new Date().toGMTString();
            String signature = generateSignature(date);

            // 2. 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", generateAuthorization(signature));
            headers.set("Date", date);
            headers.set("Host", "spark-api.xf-yun.com");
            headers.setContentType(MediaType.APPLICATION_JSON);

            // 3. 构造请求体
            Map<String, Object> payload = new HashMap<>();

            // 构造 header
            Map<String, Object> header = new HashMap<>();
            header.put("app_id", appId);
            payload.put("header", header);

            // 构造 parameter -> chat 参数
            Map<String, Object> chatParams = new HashMap<>();
            chatParams.put("domain", "generalv4");
            chatParams.put("temperature", 0.5);
            chatParams.put("max_tokens", 2048);

            Map<String, Object> chat = new HashMap<>();
            chat.put("chat", chatParams);
            payload.put("parameter", chat);

            // 设置 payload 内容
            payload.put("payload", request.get("payload"));

            // 4. 转发请求
            RestTemplate restTemplate = new RestTemplate();
            ResponseEntity<Map> response = restTemplate.exchange(
                    "https://spark-api.xf-yun.com/v4.0/chat",
                    HttpMethod.POST,
                    new HttpEntity<>(payload, headers),
                    Map.class
            );

            return ResponseEntity.ok(response.getBody());

        } catch (Exception e) {
            // 替换 Map.of(...) 为 Collections.singletonMap(...)
            return ResponseEntity.status(500).body(Collections.singletonMap("error", e.getMessage()));
        }
    }

    private String generateSignature(String date) {
        String origin = "host: spark-api.xf-yun.com\ndate: " + date + "\nGET /v4.0/chat HTTP/1.1";
        return Base64.getEncoder().encodeToString(
                HmacUtils.hmacSha256(apiSecret, origin)
        );
    }

    private String generateAuthorization(String signature) {
        String origin = String.format(
                "api_key=\"%s\", algorithm=\"hmac-sha256\", headers=\"host date request-line\", signature=\"%s\"",
                apiKey, signature
        );
        return Base64.getEncoder().encodeToString(origin.getBytes());
    }
}
